package com.tled.zyf.cookie;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "你好,你吃了吗?";
		str = URLEncoder.encode(str, "utf-8");
		System.out.println(str);

		str = URLDecoder.decode(str, "utf-8");
		System.out.println(str);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		// 获取所有 cookie
		Cookie[] cs = request.getCookies();

		// TODO 有 cookie 已解决,没有 cookie 未实现
		// 遍历
		if (cs != null && cs.length > 0) {
			for (Cookie cookie : cs) {
				// 获取名称
				String name = cookie.getName();
				// 如果名字是 lastTime 说明访问过
				if (name.equals("lastTime")) {
					// 当前时间
					Date date = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
					String dateString = sdf.format(date);

					// 上次时间,并解码
					String value = URLDecoder.decode(cookie.getValue(), "utf-8");

					// 把当前时间设置到 cookie 中,并进行编码
					cookie.setValue(URLEncoder.encode(dateString, "utf-8"));

					// 一个月
					cookie.setMaxAge(60 * 60 * 24 * 30);

					response.addCookie(cookie);

					response.getWriter().println("<h2>欢迎回来!上次回访时间为 : " + value + "</h2>");

					return;
				}
			}
		}
		// 能到这里,说明没访问到
		// 当前时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		String dateString = sdf.format(date);
		dateString = URLEncoder.encode(dateString, "utf-8");
		Cookie cookie = new Cookie("lastTime", dateString);
		cookie.setMaxAge(60 * 60 * 24 * 30);
		response.addCookie(cookie);
		response.getWriter().println("<h2>欢迎首次访问</h2>");

	}
}
